package com.xcdh.trading.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xcdh.trading.entity.AStock;
import com.xcdh.trading.entity.StockBidding;
import com.xcdh.trading.mapper.StockBiddingMapper;
import com.xcdh.trading.response.TradingRes;
import com.xcdh.trading.service.AStockService;
import com.xcdh.trading.service.StockBiddingService;
import com.xcdh.trading.util.TuShareApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class StockBiddingServiceImpl extends ServiceImpl<StockBiddingMapper, StockBidding>
    implements StockBiddingService {

    @Autowired
    private AStockService aStockService ;

    @Override
    public void syncDayBidding(String dataCode) {
        TradingRes tradingRes = TuShareApi.post("stk_auction" , dataCode);
        List<StockBidding> biddingList = tradingRes.parse(StockBidding.class);
        List<AStock> list = aStockService.list();
        Map<String, AStock> stockMap = list.stream().collect(Collectors.toMap(AStock::getTsCode, Function.identity()));
        for (StockBidding stockBidding : biddingList) {
            AStock aStock = stockMap.get(stockBidding.getTsCode());
            if(aStock != null){
                stockBidding.setName(aStock.getName());
            }
            StockBidding bidding = lambdaQuery()
                    .eq(StockBidding::getTsCode, stockBidding.getTsCode())
                    .eq(StockBidding::getTradeDate, dataCode).one();
            if(bidding == null){
                save(stockBidding) ;
            }else {
                stockBidding.setId(bidding.getId());
                updateById(stockBidding) ;
            }
        }
    }
}
